package src;

import java.io.BufferedReader;
import java.io.BufferedWriter;
//import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import lucene.LuceneConstants;


import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
//import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.ScoreDoc;

public class SearchFaq {

	IndexReader reader = null;
	Searcher searcher;
	Analyzer qanalyzer;
	QueryParser parser;
	
	public SearchFaq(String indexDir){
		try{
			reader = IndexReader.open(indexDir);
			searcher= new IndexSearcher(reader);
			qanalyzer = new  WhitespaceAnalyzer();
			parser= new QueryParser("question",qanalyzer);
		}
		catch(Exception e){
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public int totalDoc(){
		return reader.numDocs();
	}

	public Vector getHitIds(String querystr){
		Query query= null;
		Vector vec = new Vector();
		Vector score=new Vector();
			try {
				//Debug.printUTF(querystr+"\n");
				query= parser.parse(querystr);
			//	query=new FuzzyQuery(new Term("question",querystr),0.6f,2);
		//		TopDocs top=searcher.search(query,1000);
			//	ScoreDoc[] scores=top.scoreDocs;
				Hits hits= searcher.search(query);
				for(int i=0; i<hits.length(); i++){
				//for(int i=0; i<top.totalHits; i++){
			  vec.addElement(new Integer(hits.id(i)));
		//		vec.addElement(new Token(new Integer(scores[i].doc).toString(),scores[i].score));
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/*if(querystr.equals("अध्‍ययन")){
				Debug.printHitId(vec);
				System.exit(-1);
			}*/
			return vec;
	}
	
	public void closeSearcher(){ 	
		try {
			searcher.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Vector search(String querystr){
		Query query= null;
		Vector vec = new Vector();
			try {
				query= parser.parse(querystr);
				Hits hits= searcher.search(query);
				for(int i=0; i<hits.length(); i++){
					Document doc= hits.doc(i);
					float score=hits.score(i);
					Field questionfield = doc.getField("question");
					Debug.printUTF(questionfield.stringValue()+"\n");
					Field answerfield = doc.getField("answer");
					Field docnum = doc.getField("docnum");
					QApair qap = new QApair(questionfield.stringValue(),answerfield.stringValue(),docnum.stringValue(),score); 
					vec.addElement(qap);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return vec;
	}
	
	public QApair getDocFromSingleId(int hitId){
		QApair qap= null;
		try {
			Document doc = searcher.doc(hitId);
			Field questionfield = doc.getField("question");
			Field answerfield = doc.getField("answer");
			Field docnum = doc.getField("docnum");
			qap = new QApair(questionfield.stringValue(),answerfield.stringValue(),docnum.stringValue(),0);
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return qap;
	}
	
	public Vector getDocsFromIds(Vector ids){
		Vector vec = new Vector();
		if(ids == null){
			return null;
		}
		for(int i=0; i< ids.size(); i++){
			MyDoc md = (MyDoc)ids.get(i);
			Document doc;
			try {
				doc = searcher.doc(md.hitId);
				Field questionfield = doc.getField("question");
				Field answerfield = doc.getField("answer");
				Field docnum = doc.getField("docnum");
				QApair qap = new QApair(questionfield.stringValue(),answerfield.stringValue(),docnum.stringValue(),0); 
				vec.addElement(qap);
				
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return vec;
	}
	public int docFreq (String token) throws IOException{
		return reader.docFreq(new Term("question",token));
	}
	
	public  Vector createQuery(String query, double fuzzy){
		 
		Vector vec = new Vector();
		try {
			
			//Query query1 = parser.parse(query);
			//System.out.println(query1.toString());
			String [] tokens = query.split("[ ]+");
			//System.out.println(tokens[0]);
			
			String completeQuery = tokens[0]+"~"+fuzzy;
			for(int i=1; i<tokens.length; i++){
				completeQuery = completeQuery+" "+tokens[i]+"~"+fuzzy; 
			}
			Query query1 = parser.parse(completeQuery);
			//System.out.println(query1.toString());
			Hits hits= searcher.search(query1);
			for(int i=0; i<Math.min(hits.length(), 1); i++){
				Document doc= hits.doc(i);
				float score=hits.score(i);
				Field questionfield = doc.getField("question");
				Field answerfield = doc.getField("answer");
				Field docnum = doc.getField("docnum");
				QApair qap = new QApair(questionfield.stringValue(),answerfield.stringValue(),docnum.stringValue(),score); 
				vec.addElement(qap);
			}
			//FuzzyQuery fq = new FuzzyQuery(new Term("question",tokens[0]));
			//System.out.println(fq.toString());
			return vec;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	public void getSingleLuceneResult(SearchFaq sf, String smsQuery, double fuzzy){
		Vector doclist = sf.createQuery(smsQuery,fuzzy);
		System.out.println(smsQuery);
		
		for(int i=0; i< doclist.size(); i++){
			QApair qap = (QApair)doclist.get(i);
			System.out.println(qap.quest);
		}
	}
	
	public void getLuceneResult(SearchFaq sf, String queryFile, String resultFile, double fuzzy){
	
		String smsQuery = null;
		int count = 1;
			try {
				BufferedReader filereader = new BufferedReader(new FileReader(queryFile));
				BufferedWriter filewriter = new BufferedWriter(new FileWriter(resultFile, true));
				while((smsQuery = filereader.readLine())!= null){
					Vector doclist = sf.createQuery(smsQuery,fuzzy);
					System.out.println(count);
					
					filewriter.write(count+" : "+smsQuery);
					count++;
					filewriter.newLine();
					//filewriter.newLine();
					for(int i=0; i< doclist.size(); i++){
						QApair qap = (QApair)doclist.get(i);
						filewriter.write(qap.quest);
						filewriter.newLine();
					}
					filewriter.write("-----------------------------------------");
					filewriter.newLine();
					filewriter.newLine();
				}
				filereader.close();
				filewriter.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}
	public static void main(String[] args) {
		
		double fuzzy = 0.6;
		SearchFaq sf = new SearchFaq(LuceneConstants.hindiFAQIndexdir_DanishData);
		//sf.getLuceneResult(sf,SMSConstant.yahooQueryFile,SMSConstant.yahooLuceneResultFile,fuzzy);
		//SearchFaq sf = new SearchFaq(LuceneConstants.faqindexdir);
		//sf.getLuceneResult(sf,SMSConstant.SMSqueryFile,SMSConstant.mobileLuceneResultFile,fuzzy);
		//sf.getLuceneResult(sf,SMSConstant.tempLuceneQueryFile,SMSConstant.tempLuceneResultFile);
		String smsQuery = "prce  rplcng cykl cbl";
		sf.search("खेल");
		//sf.getSingleLuceneResult(sf, smsQuery, fuzzy);
		/*
		//String query = "advntg of hang tecnik in lng jmp";
		//Vector doclist = sf.createQuery(query);
		
		//Vector doclist = sf.search("people");
		QApair qap = null;
		
		
		for(int i=0;i<doclist.size();i++){
			qap = (QApair)doclist.get(i);
			//System.out.println(qap.docnum);
			//System.out.println(qap.luceneScore);
			System.out.println(qap.quest);
			//System.out.println(qap.ans);
		}
		/*
		Vector doclist = sf.getHitIds("cell");
		for(int i=0;i<doclist.size();i++){
			Integer in = (Integer)doclist.get(i);
			System.out.println(in.intValue());
			
		}*/
	}
}
